package com.atguigu;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @date 2021/8/6
 * @desc 三个售票员卖出50张票
 */
public class SaleTicketDemo2 {
    public static void main(String[] args) {
        Ticket2 ticket = new Ticket2();

        new Thread(() -> {
            for (int i = 0; i < 51; i++) {
                ticket.sale();
            }
        }, "张三").start();

        new Thread(() -> {
            for (int i = 0; i < 51; i++) {
                ticket.sale();
            }
        }, "李四").start();
        new Thread(() -> {
            for (int i = 0; i < 51; i++) {
                ticket.sale();
            }
        }, "王五").start();
    }


}

class Ticket2 {
    int number = 50;
    private Lock lock = new ReentrantLock();


    public void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了第" + (50 - number + 1) + "张票,还剩下" + (number - 1) + "张票");
                number--;
            }
        } finally {
            lock.unlock();
        }
    }
}


